import React, { FormEvent } from 'react'
import { useAuth } from 'context/auth-context'
import { Form, Input, Button } from 'antd'
import { LongButton } from 'unauthenticated-app'
import { useAsync } from 'utils/use-async'
export const RegisterScreen = ({ onError }: { onError: (e: Error) => void }) => {
  const { register } = useAuth()
  const { run, isLoading } = useAsync()

  const handleSubmit = async ({ cpassword, ...value }: { cpassword: string; username: string; password: string }) => {
    if (cpassword !== value.password) {
      return onError({ message: '请确认输入的两次密码相同' } as any)
    }
    await run(register(value)).catch((e: Promise<any>) => {
      e.then(error => onError(error))
    })
  }

  return (
    <div>
      <Form onFinish={handleSubmit}>
        <Form.Item name={'username'} rules={[{ required: true, message: '请输入用户名' }]}>
          <Input placeholder={'用户名'} type="text" id={'username'} />
        </Form.Item>
        <Form.Item name={'password'} rules={[{ required: true, message: '请输入密码' }]}>
          <Input placeholder={'密码'} type="password" id={'password'} />
        </Form.Item>
        <Form.Item name={'cpassword'} rules={[{ required: true, message: '请确认密码' }]}>
          <Input placeholder={'确认密码'} type={'password'} id={'cpassword'} />
        </Form.Item>

        <LongButton loading={isLoading} htmlType={'submit'} type={'primary'}>
          注册
        </LongButton>
      </Form>
    </div>
  )
}
